<?php

require_once "database.php";
require_once 'common.php';
/* given a person returns an associative array containing that person's:
		- name - name
		- birth date - bdate
		- death date - ddate
		- photo - imgloc
		- age - age
		- roles (actor, director, etc.) - roles
		- average reception - avgrank
		- average salary - avgsal
*/
function getBioInfo($id) {
	$conn = open_db();
	$id = mysql_real_escape_string($id);
	$def = "unknown";	
	$def_image = "_images/silhouette_head.jpg";

	$info = array("name" => $def, "bdate" => $def, "ddate" => "", "imgloc" => $def_image, 
		"age" => $def, "roles" => $def, "avgrank" => $def, "avgsal" => $def);

	$id_query = mysql_query("select * from persons where person_id=$id");
	$id_data = mysql_fetch_array($id_query);
	$name = $id_data["name"];
	$info["name"] = $name;

	$result = mysql_query("select person_id, name, date_format(birth_date, '%M %e, %Y') birth_date, date_format(death_date, '%M %e, %Y') death_date, floor(datediff(death_date, birth_date)/365) ageIfDead, floor(datediff(now(), birth_date)/365) ageIfAlive, photo_url from persons where name='$name'");
	if (mysql_num_rows($result) == 0)
		return $info;
	$person = mysql_fetch_array($result);

	$info['name'] = $person['name'];
	$info['bdate'] = $person['birth_date'];
	$info['ddate'] = $person['death_date'];
	$info['age'] = empty($info['ddate']) ? $person['ageIfAlive'] : $person['ageIfDead'];

	if ($person['photo_url'] != NULL)
		$info['imgloc'] = $person['photo_url'];

	$result = mysql_query("select distinct job_title from jobs natural join persons where name='$name'");
	$roles = array();
	while ($role = mysql_fetch_array($result))
		$roles[] = $role['job_title'];
	$info['roles'] = implode(', ', $roles);

	$rating_info = mysql_fetch_array(mysql_query("select round(sum(rating)/count(*), 1) avgRating from projects natural join jobs where person_id='$id' and votes > 1300 and title not like '\"%' and other=''"));
	$info['avgrank'] = $rating_info['avgRating'];

	$info['name'] = getPrettyName($name);

	close_db($conn);
	return $info;
}

function getID($name) {
	$conn = open_db();
	$name = mysql_real_escape_string($name);	
	$id_query = mysql_query("select * from persons where name='$name'");
	$id_data = mysql_fetch_array($id_query);
	
	close_db($conn);
	
	return $id_data["person_id"];
}

function getEmptySearchResultText($searchText) {
	$errorText = "<div id='no_search_results_text'>
		Your search did not produce any results.<br /><br />
		Possible Solutions:
		<ul>
			<li>Make sure that the name you entered is spelled correctly.</li>
			<li>If you entered a movie title, your search will not work correctly; 
			try searching for an actor in that movie, instead.</li>
		</ul></div>
		";
	return $errorText;
}

/*
	Returns an associative array that contains:
		"career" =>  the url of a chart image displaying the number of movies per year
		"reception" => the url of a chart image displaying the average reception per year
*/
function getBasicCharts($id) {
	$conn = open_db();
	$id = mysql_real_escape_string($id);
	$jobs = mysql_query("select year,rating from projects natural join jobs where person_id=$id and title not like '\"%' and other='' order by year");
	close_db($conn);

	while ($job = mysql_fetch_array($jobs)) {
		if ($job['rating'] != NULL) {
			if ($receptionInfo[$job['year']]) {
				$receptionInfo[$job['year']]['projects']++;
				$receptionInfo[$job['year']]['rating'] += $job['rating'];
			} else
				$receptionInfo[$job['year']] = array('projects'=>1, 'rating'=>$job['rating']);
		}
		$careerInfo[$job['year']] = ($careerInfo[$job['year']])?($careerInfo[$job['year']]+1):1;
	}

	$i = 0;
	foreach ($receptionInfo as $year=>$receptionData) {
		$years[$i] = $year;	
		$ratings[$i] = $receptionData['rating']/$receptionData['projects'];
		$projects[$i++] = $receptionData['projects'];
	}
	
	$minX = min($years);
	$maxX = max($years);
	$receptionUrl = "http://chart.apis.google.com/chart?cht=lxy&chxt=x,y&chs=350x250&chco=9d55bf&chls=1.5,1,0&chm=B,f9edff,0,0,0&chg=0,10,1,5&chd=t:";
	$receptionUrl .= implode(',', $years) . "|" . implode(',', $ratings) . "&chds=$minX,$maxX,0,10" . "&chxr=0,$minX,$maxX|1,0,10";	
	$charts['reception'] = $receptionUrl;

	$i = 0;
	foreach ($careerInfo as $year=>$numberOfProjects)
		$yearsWithMovies[$i++] = $year;
	
	$minX = min($yearsWithMovies);
	$maxX = max($yearsWithMovies);

	for ($i=$minX;$i<=$maxX;$i++)
		$projAllYears[$i] = ($careerInfo[$i])?$careerInfo[$i]:0;

	$careerUrl = getBasePath()."/graph.php?xMin=$minX&xMax=$maxX&w=350&h=250&vals=" . implode(',', $projAllYears) ."&yMax=".(max($projAllYears)+1);
	$charts['career'] = $careerUrl;	

	return $charts;
}

/*
	Removes all parenthesized numerals and returns the person's name in the form: First Last
*/
function getPrettyName($name) {
	$nameArr = explode(",", $name);
	return preg_replace("/\(.*\)/", "", "$nameArr[1] $nameArr[0]");
}

/*
	Returns an associative that contains:
		"pie" => the url of a pie chart image containing the top five genres
		"line" => the url of a line chart image containing the number of movies in
			the top three genres per year
*/
function getGenreCharts($id) {
	$conn = open_db();
	$id = mysql_real_escape_string($id);
	$genre_query = mysql_query("select genre, count(*) as num from projects natural join jobs natural join genres where person_id=$id and title not like '\"%' and other='' group by genre order by num desc limit 5");

	$result = "<div class='list_box'><ol><div class='list_box_left'>";
	$ctr = 0;
	while ($genre = mysql_fetch_array($genre_query)) {
		$genres[$ctr] = $genre['genre'];
		if ($ctr++ == 5) 
			$result .= "</div>";
		
		$result .= "<li><span class='genre_title'>" . $genre['genre'] . "</span> (" . $genre['num'] . " movies)</li>";
		$genre_d[$genre['genre']] = $genre['num'];
	}

	$url1= "http://chart.apis.google.com/chart?cht=p3&chco=66ef90&chs=500x180&chd=t:";
	
	$sum_n = 0;
	foreach ($genre_d as $g=>$n) {
			$sum_n += $n;
	}

	$vals = array();
	$gens = array();
	$ctr = 0;
	foreach ($genre_d as $g=>$n) {
		$tmp = $n;
		$n = ($n/$sum_n)*100;
		$vals[$ctr] = $n;
		$gens[$ctr++] = "$g ($tmp)";
	}

	$url1 .= implode(',', $vals) . "&chl=" . implode('|', $gens);

	$url = "http://chart.apis.google.com/chart?cht=lxy&chxt=x,y&chs=763x250&chco=3072F3,e7cc4d,8be191,d99cde,f4afaf&chls=1,1,0&chm=o,3072f3,0,-1,6|s,e7cc4d,1,-1,6|d,8be191,2,-1,6|x,d99cde,3,-1,6|c,f4afaf,4,-1,6&chd=t:";

	$num_genres = 3;
	for ($i=0; $i<$num_genres; $i++) {
		if ($genres[$i]) {
			$query2 = mysql_query("select year, count(*) as num from jobs natural join projects natural join genres where person_id=$id and title not like '\"%' and other='' and genre='$genres[$i]' group by year order by year;");
			
			while ($year_info = mysql_fetch_array($query2)) {
				if ($genre_data[$i]) {
					$genre_data[$i][$year_info['year']] = $year_info['num'];
				} else {
					$genre_data[$i] = array($year_info['year']=>$year_info['num']);
				}
			}
		}
	}

	$min_x = 99999999;
	$max_x = 0;
	$max_y = 0;

	foreach ($genre_data as $num=>$data) {
		$year_data=array();
		$movies_data=array();
		$i = 0;
		foreach ($data as $year=>$movies) {
			if ($year > $max_x)
				$max_x = $year;
			if ($year < $min_x)
				$min_x = $year;
			if ($movies > $max_y)
				$max_y = $movies;
			
			$year_data[$i] = $year;
			$movies_data[$i++] = $movies;
		}
		$genres2[$num] = implode(',', $year_data) . "|" . implode(',', $movies_data);
	}
	
	$min_x -= 1;
	$max_x += 1;
	$max_y +=1;
	$url .= implode('|', $genres2) . "&chds=";
	for ($i=0; $i < $num_genres;$i++) {
		$scaling_data[$i] = "$min_x,$max_x,0,$max_y";
		$key_data[$i] = $genres[$i];
	}

	$url .= implode(',', $scaling_data) . "&chdl=" . implode('|', $key_data) . "&chxr=0,$min_x,$max_x|1,0,$max_y";

	close_db($conn);
	
	$info['pie'] = $url1;
	$info['line'] = $url;
	return $info;
}

function getTopCollaborators($id) {
	$conn = open_db();
	$id = mysql_real_escape_string($id);
	$personPos = 10;
	$collabPos = 15;
	$collaborators = mysql_query("select a.person_id as pid, name, count(*) as num from projects natural join persons natural join jobs as a left join jobs as b on a.project_id = b.project_id where b.person_id=$id and a.person_id<>b.person_id and ((a.billing_position < $collabPos and a.billing_position <> 0) or a.billing_position is null) and ((b.billing_position < $personPos and b.billing_position <> 0) or b.billing_position is null) and title not like '\"%' and other='' group by a.person_id order by num desc");
	close_db($conn);

	$ret = "<ol>";
	$i=0;
	while (($collaborator = mysql_fetch_array($collaborators)) && $i++<10) {

		$ret .= "<li><a href='" . getBasePath() . "/person/" . $collaborator['pid'] ."'>" . getPrettyName($collaborator['name']) . "</a></li>";
	}
	$ret .= "</ol>";
	if ($i == 0)
		$ret = "<div class='no_info'>Not enough information available.</div>";

	return $ret;
}

?>
